﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;

using SBPweb.PlAzureNet.Shared.Library.Actors;

using SBPweb.PlAzureNet.Server.Data.Actors;
using SBPweb.PlAzureNet.Server.Data.Context;

using SBPweb.PlAzureNet.Server.Library.Operations;

namespace SBPweb.PlAzureNet.Server.Library.Strategies
{

    internal static class ActionResultsGenerator
    {

        private static Random rnd;

        static ActionResultsGenerator()
        {
            rnd = new Random((int)DateTime.Now.Ticks);
        }

        internal static IEnumerable<long> FetchAllClosableRoundIds()
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                return context.Rounds.Where(x => !x.IsClosed).Select(x => x.Id).ToList();
                //DateTime dt = DateTime.Today.AddDays(-1);
                //return context.Rounds.Where(x => !x.IsClosed && x.Date == dt).Select(x => x.Id);
            }
        }

        internal static void CloseRound(long roundId)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                context.Connection.Open();
                DbTransaction transaction = context.Transaction = context.Connection.BeginTransaction();
                try
                {
                    Round round = context.Rounds.FirstOrDefault(x => x.Id == roundId);
                    foreach (var s in round.Actions.GroupBy(x => x.PleasureId))
                    {
                        GenerateResults(context, roundId, s.Key, s.ToList());
                    }

                    round.IsClosed = true;

                    context.SubmitChanges();

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    if (transaction != null)
                    {
                        transaction.Rollback();
                    }
                    Console.WriteLine(ex);
                }
                finally
                {
                    context.Connection.Close();
                }
            }
        }

        private static void GenerateResults(DataTablesContext context, long roundId, int pleasureId, IEnumerable<Data.Actors.Action> actions)
        {
            decimal? plSum = context.SumActionQuantities(roundId, pleasureId, (int)ActionTypes.Give);

            var top = actions.Where(x => x.Request == (int)ActionTypes.Take).OrderBy(x => x.Person.Rank).Take(10);

            int index = rnd.Next(0, top.Count());

            var action = top.ElementAt(index);

            action.Result = (int)ActionTypes.Give;
            action.ReceivedQuantity = plSum;
        }

    }

}